﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

public class BaseController : Controller
{

    protected BaseController() { 

    }
    /// <summary>
    /// 读取controller及action方便做权限判断
    /// </summary>
    /// <param name="filterContext"></param>
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //controller
        var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
        //action
        var actionName = filterContext.ActionDescriptor.ActionName;
        //获取参数数组
        var arrParameter = filterContext.ActionDescriptor.GetParameters();

        //根据索引获取对应参数名 
        //如果可以确定参数名称可以直接用ActionParameters通过Key来获取，Key指参数名称
        #region
        if (controllerName == "RestFul")
        {
            var keys = filterContext.ActionParameters["keys"];
            if (keys == null)
            {
              //  filterContext.Result = IsNoAuthority();
            }
        }
        #endregion


         //留一个后门，测试方便。发布的时候一定要删除该代码。
                   //if (LoginUser.UName == "itcast")
                   //{
                   //    return;
                   //}
                    //完成权限校验。
                    //获取用户请求的URL地址.
                   string url = Request.Url.AbsolutePath.ToLower();
                    //获取请求的方式.
                   string httpMehotd = Request.HttpMethod;
                    //根据获取的URL地址与请求的方式查询权限表。
                //   IApplicationContext ctx = ContextRegistry.GetContext();
                //   IBLL.IActionInfoService ActionInfoService = (IBLL.IActionInfoService)ctx.GetObject("ActionInfoService");
                //  var actionInfo= ActionInfoService.LoadEntities(a=>a.Url==url&&a.HttpMethod==httpMehotd).FirstOrDefault();
                //  if (actionInfo != null)
                //  {
                //      filterContext.Result = Redirect("/Error.html");
                //      return;
                //  }
 
                //    //判断用户是否具有所访问的地址对应的权限
                //   IUserInfoService UserInfoService = (IUserInfoService)ctx.GetObject("UserInfoService");
                //   var loginUserInfo = UserInfoService.LoadEntities(u=>u.ID==LoginUser.ID).FirstOrDefault();
                //    //1:可以先按照用户权限这条线进行过滤。
                //   var isExt =(from a in loginUserInfo.R_UserInfo_ActionInfo
                //               where a.ActionInfoID == actionInfo.ID
                //               select a).FirstOrDefault();
                //   if (isExt != null)
                //   {
                //       if (isExt.IsPass)
                //       {
                //           return;
                //       }
                //       else
                //       {
                //           filterContext.Result = Redirect("/Error.html");
                //           return;
                //       }
 
                //   }
                //    //2：按照用户角色权限这条线进行过滤。
                //   var loginUserRole = loginUserInfo.RoleInfo;
                //   var count = (from r in loginUserRole
                //               from a in r.ActionInfo
                //               where a.ID == actionInfo.ID
                //               select a).Count();
                //   if (count < 1)
                //   {
                //       filterContext.Result = Redirect("/Error.html");
                //       return;
                //   }
                    
 
                //}
               
     





        base.OnActionExecuting(filterContext);         
    }
    /// <summary>
    /// 初始化
    /// </summary>
    /// <param name="requestContext"></param>
    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext); 
         bool IsOK = false;
            //获取当前访问页面地址
            //string requestPath = RequestHelper.GetScriptName;
            string requestPath = "";
            string[] filterUrl = { //无需授权能打开的界面
 
            };//过滤特别页面
            //对上传的文件的类型进行一个个匹对
            for (int i = 0; i < filterUrl.Length; i++)
            {
                if (requestPath == filterUrl[i])
                {
                    IsOK = true;
                    break;
                }
            }
            if (!IsOK)
            {
                //string UserId = filterContext.Controller.ViewData["AccountName"];
                //string UserId = RequestSession.GetSessionUser().UserId.ToString();//用户ID
                //DataTable dt = sys_idao.GetPermission_URL(UserId);
                //DataView dv = new DataView(dt);
                //dv.RowFilter = "NavigateUrl = '" + requestPath + "'";
                //if (dv.Count == 0)
                //{
                //    StringBuilder strHTML = new StringBuilder();
                //    strHTML.Append("<div style='text-align: center; line-height: 300px;'>");
                //    strHTML.Append("<font style=\"font-size: 13;font-weight: bold; color: red;\">权限不足</font></div>");
                //    requestContext.HttpContext.Response.Write(strHTML);
                //    requestContext.HttpContext.Response.End();
                //}
            } 
 
    }
    /// <summary>
    /// 捕捉500错误 404需要配置
    /// </summary>
    /// <param name="filterContext"></param>
    protected override void OnException(ExceptionContext filterContext)
    {
        // 错误日志编写    
        string controllerNamer = filterContext.RouteData.Values["controller"].ToString();
        string actionName = filterContext.RouteData.Values["action"].ToString();
        string exception = filterContext.Exception.ToString();
        // 执行基类中的OnException    
        base.OnException(filterContext);  
    }
    public JsonResult IsNoAuthority()
    {
        JsonStatus status = new JsonStatus("-1", "无权访问接口，请授权");
        var json = new JsonResult();
        json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        json.Data = status;
        return json;
    }
    public class JsonStatus
    {
        public string code { set; get; }
        public string error { set; get; }
        public JsonStatus()
        {

        }
        public JsonStatus(string _code, string _error)
        {
            this.code = _code;
            this.error = _error;
        }
    }
} 